<template>
	<view class="template-project">
		<view class="tn-bg-white tn-safe-area-inset-bottom" style="border-radius: 50rpx 50rpx 0 0;">
			<!-- 标题栏 -->
			<view class="title-bar">
				<text class="title-text">活动</text>
			</view>
			<!-- 状态栏（标签栏） -->
			<view class="tab-bar">
				<view class="tab-item" :class="{active: currentTab === 'all'}" @click="switchTab('all')">全部</view>
				<view class="tab-item" :class="{active: currentTab === 'ongoing'}" @click="switchTab('ongoing')">进行中
				</view>
				<view class="tab-item" :class="{active: currentTab === 'upcoming'}" @click="switchTab('upcoming')">未开始
				</view>
				<view class="tab-item" :class="{active: currentTab === 'ended'}" @click="switchTab('ended')">已结束</view>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading && activitiesList.length === 0" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 空数据状态 -->
			<view v-else-if="activitiesList.length === 0" class="empty-container">
				<image class="empty-image" src="/static/empty.png" mode="aspectFit"></image>
				<text class="empty-text">暂无活动数据</text>
			</view>

			<!-- 活动列表 -->
			<view v-else class="tn-padding-bottom-lg">
				<block v-for="(item, index) in filteredContent" :key="item.id || index">
					<view class="tn-blogger-content__wrap" @click="goToDetail(item)">
						<!-- 图片区域 -->
						<view class="image-container">
							<image class="tn-blogger-content__main-image tn-blogger-content__main-image--1"
								:src="item.coverImage[0]" mode="aspectFill" @error="handleImageError(item)"></image>
							<!-- 状态标签 -->
							<view class="status-tag" :class="item.status">
								{{ statusTextMap[item.status] }}
							</view>
						</view>
						<!-- 活动信息 -->
						<view class="activity-info-wrapper">
							<view class="title-container">
								<text class="activity-title">{{ item.title }}</text>
							</view>
							<view class="time-info">
								<view class="time-item tn-color-gray">
									<image class="time-icon" :src="timeIconUrl" mode="widthFix"></image>
									<text>{{ item.startTime }}至{{ item.endTime }}</text>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
		</view>

		<!-- 发布按钮 -->
		<view class="floating-action-btn" @click="goToCreateActivity">
			<view class="fab-icon">
				<text class="tn-icon-add tn-color-white"></text>
			</view>
		</view>
	</view>
</template>

<script>
	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
	export default {
		name: 'Activity',
		mixins: [template_page_mixin],
		data() {
			return {
				currentTab: 'all',
				statusTextMap: {
					ongoing: '进行中',
					upcoming: '未开始',
					ended: '已结束'
				},
				timeIconUrl: '/static/activityImg/time.png',
				activitiesList: [], // 接口数据存储
				loading: false, // 加载状态
				page: 1, // 分页页码
				pageSize: 10 // 每页条数
			}
		},
		computed: {
			filteredContent() {
				console.log(`[活动筛选] 当前标签: ${this.currentTab}，总数据量: ${this.activitiesList.length}`);
				if (this.currentTab === 'all') {
					return this.activitiesList;
				} else {
					return this.activitiesList.filter(item => item.status === this.currentTab);
				}
			}
		},
		methods: {
			onTabShow() {
				console.log("加载数据");
				this.page = 1; // 重置页码
				this.getActivities(); // 加载第一页数据
			},
			switchTab(tabType) {
				this.currentTab = tabType;
			},
			// 加载活动列表（核心接口请求）
			getActivities() {
				return new Promise((resolve) => {
					this.loading = true;
					console.log(`[接口请求] 开始请求活动列表，页码: ${this.page}，地址: http://localhost:8080/api/activities/list`);

					uni.request({
						url: 'http://localhost:8080/api/activities/list',
						method: 'GET',
						data: {
							page: this.page,
							pageSize: this.pageSize
						},
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							console.log('[接口响应] 活动列表请求成功，原始响应:', res);
							const response = res.data;

							if (response.code === 200) {
								const newData = response.data || [];
								console.log(`[数据处理] 接口返回${newData.length}条活动数据`);

								// 处理数据格式（适配前端模板）
								const formattedData = newData.map(item => ({
									...item,
									// 状态转换（根据后端实际值调整）
									status: this.mapStatus(item.status),
									// 封面图处理（确保数组格式）
									coverImage: item.coverImage ? [item.coverImage] : [
										'/static/activityImg/default.jpg'
									],
									// 时间格式处理（示例：后端返回时间戳时转换）
									startTime: this.formatTime(item.startTime),
									endTime: this.formatTime(item.endTime)
								}));

								// 合并数据（首次加载/分页加载）
								this.activitiesList = this.page === 1 ?
									formattedData : [...this.activitiesList, ...formattedData];

								console.log(`[数据处理] 格式化完成，当前总数据量: ${this.activitiesList.length}`);
							} else {
								const errorMsg = response.msg || '获取活动列表失败';
								console.error(`[接口响应] 接口返回错误: ${errorMsg}`);
								uni.showToast({
									title: errorMsg,
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							console.error('[接口请求] 活动列表请求失败:', err);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						},
						complete: () => {
							this.loading = false;
							console.log(`[接口请求] 活动列表请求完成，页码: ${this.page}`);
							resolve(); // 解决Promise，用于下拉刷新结束
						}
					});
				});
			},
			// 状态映射（根据后端实际状态值调整）
			mapStatus(backendStatus) {
				// 示例：假设后端用0=未开始，1=进行中，2=已结束
				const statusMap = {
					0: 'upcoming',
					1: 'ongoing',
					2: 'ended'
				};
				return statusMap[backendStatus] || 'upcoming';
			},

			formatTime(timeStr) {
				if (!timeStr) return '';
				// 处理格式："2023-10-15 09:00:00" → "2023年10月15日 09:00"
				// 先按空格分割日期和时间
				const [datePart, timePart] = timeStr.split(' ');
				if (!datePart) return '';

				// 分割年月日（处理 "2023-10-15"）
				const [year, month, day] = datePart.split('-');
				// 处理时间部分（取前5位，如 "09:00:00" → "09:00"）
				const formattedTime = timePart ? timePart.slice(0, 5) : '';

				// 拼接成 "2023年10月15日 09:00"
				return `${year}年${month}月${day}日${formattedTime ? ' ' + formattedTime : ''}`;
			},

			// 图片加载失败处理
			handleImageError(item) {
				console.log(`[图片错误] 封面图加载失败，使用默认图: ${item.id}`);
				item.coverImage[0] = '/static/activityImg/default.jpg';
			},
			// 跳转详情页并传递当前活动数据
			goToDetail(activity) {
				uni.navigateTo({
					url: '/preferredPages/activityDetail', // 详情页路径
					success: (res) => {
						// 通过事件通道传递数据
						res.eventChannel.emit('passActivityData', {
							data: activity
						});
					}
				});
			},
			// 跳转到活动发布页面
			goToCreateActivity() {
				uni.navigateTo({
					url: '/circlePages/create' // 活动发布页面路径，请根据实际情况修改
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.title-bar {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.title-text {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 100rpx;
		padding: 0 30rpx;
		background-color: #007356;
		color: white;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.tab-bar {
		display: flex;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		flex: 1;
		padding: 30rpx 0;
		text-align: center;
		font-size: 28rpx;
		color: #999;
		position: relative;
	}

	.tab-item.active {
		color: #007356;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 6rpx;
		background-color: #007356;
		border-radius: 3rpx;
	}

	.image-container {
		position: relative;
	}

	.status-tag {
		position: absolute;
		top: 15rpx;
		right: 15rpx;
		padding: 8rpx 15rpx;
		color: white;
		font-size: 24rpx;
		font-weight: bold;
		border-radius: 6rpx;
		z-index: 10;
	}

	.status-tag.ongoing {
		background-color: #00B42A;
	}

	.status-tag.upcoming {
		background-color: #FF7D00;
	}

	.status-tag.ended {
		background-color: #999999;
	}

	/* 活动信息容器 - 统一控制内边距和间距 */
	.activity-info-wrapper {
		padding: 25rpx 30rpx;
		box-sizing: border-box;
		/* 确保内边距不影响宽度计算 */
	}

	/* 标题容器：消除默认缩进 */
	.title-container {
		margin: 0;
		padding: 0;
	}

	/* 标题样式：明确字体属性，确保左对齐 */
	.activity-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		line-height: 44rpx;
		display: inline-block;
		/* 确保内容从左侧开始 */
	}

	/* 时间信息区域调整 */
	.time-info {
		margin-top: 15rpx;
		margin-bottom: 0;
		padding: 0;
		/* 移除可能的默认内边距 */
	}

	.time-icon {
		width: 26rpx;
		height: 26rpx;
		margin-right: 8rpx;
		vertical-align: middle;
	}

	.time-item {
		font-size: 24rpx;
		line-height: 36rpx;
		display: flex;
		align-items: center;
		padding: 0;

		.iconfont {
			margin-right: 8rpx;
			font-size: 26rpx;
		}
	}

	.organizer {
		font-size: 26rpx;
		color: #333;
		line-height: 36rpx;
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
		padding: 0;

		.iconfont {
			margin-right: 8rpx;
			color: #007356;
			font-size: 28rpx;
		}
	}

	.tn-blogger-content {
		&__wrap {
			box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.09);
			border-radius: 20rpx;
			margin: 30rpx;
			overflow: hidden;
		}

		&__label {
			/* 移除可能导致冲突的样式 */
			margin: 0 !important;
			padding: 0 !important;

			&__title {
				line-height: 80rpx;
				color: #333;
			}

			&__item {
				line-height: 45rpx;
				padding: 0 20rpx;
				margin: 5rpx 18rpx 0 0;

				&--prefix {
					color: #00FFC6;
					padding-right: 10rpx;
				}
			}
		}

		&__main-image {
			border-radius: 16rpx 16rpx 0 0;

			&--1 {
				width: 100%;
				height: 300rpx;
				display: block;
			}
		}

		&__count-icon {
			font-size: 40rpx;
			padding-right: 5rpx;
		}
	}

	.tn-custom-nav-bar__back {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}

	.bg-contaniner {
		position: fixed;
		top: -0rpx;
		left: -300rpx;
		--text-color: hsl(0 95% 60%);
		--bg-color: hsl(0 0% 100%);
		--bg-size: 200px;
		height: 100%;
		display: grid;
		place-items: center;
		place-content: center;
		overflow: hidden;
		background-color: var(--bg-color);
		z-index: -1;
	}

	.bg-contaniner::before {
		--size: 150vmax;
		content: "";
		inline-size: var(--size);
		block-size: var(--size);
		background-image: url("https://resource.tuniaokj.com/images/animate/animate3.png");
		background-size: var(--bg-size);
		background-repeat: repeat;
		transform: rotate(45deg);
		opacity: 0.25;
		animation: bg 6s linear infinite;
	}

	@media (prefers-reduced-motion: reduce) {
		.bg-contaniner::before {
			animation-duration: 0s;
		}
	}

	@keyframes bg {
		to {
			background-position: 0 calc(var(--bg-size) * -1);
		}
	}

	/* 悬浮按钮样式 */
	.floating-action-btn {
		position: fixed;
		bottom: 120rpx;
		right: 40rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #007356, #4caf50);
		box-shadow: 0 8rpx 30rpx #007356;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
		transition: all 0.3s ease;
	}

	.floating-action-btn:active {
		transform: scale(0.95);
		box-shadow: 0 4rpx 15rpx #007356;
	}

	.fab-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.fab-icon .tn-icon-add {
		font-size: 40rpx;
		font-weight: bold;
	}
</style>